/**
 * 
 */
package com.yinhai.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yinhai.adapter.ContactAdpter;
import com.yinhai.asynctask.BaseTask;
import com.yinhai.constant.Contact;
import com.yinhai.model.UserUserContact;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.NullUtils;

/**
 * @author 20150128通讯录功能
 * 
 */
public class ContactGroupFragment extends Fragment implements OnScrollListener {
    private ListView groupListView;
    
    private ContactAdpter smsAdpter;
    
    private ContactUserServiceImpl contactUserService;
    
    private Context context;
    
    private EditText editText;
    
    private CheckBox checkBox;
    
    private boolean isGroup = true;
    
    private ImageView head_btn_back;
    
    private View progressView;
    
    private int visibleLastIndex = 0; // 最后的可视项索引
    
    private int visibleItemCount; // 当前窗口可见项总数
    
    String clickId = "";
    
    private boolean flag = false;// 不是点击本地通讯录
    
    private String companyID = null;
    
    private List<UserUserContact> rootCompanys = new ArrayList<UserUserContact>();
    
    private List<UserUserContact> datas = new ArrayList<UserUserContact>();
    
    private Stack<String> parentIds = new Stack<String>();
    
    private TextView headTitleView;
    private SharedPreferences sharedPreferences;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();
        
        View loadMoreView = getActivity().getLayoutInflater().inflate(R.layout.load_more, null);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        progressView = loadMoreView.findViewById(R.id.pg);
        
        View view = inflater.inflate(R.layout.main_contact, null);
        contactUserService = new ContactUserServiceImpl(this.getActivity());
        headTitleView = (TextView)view.findViewById(R.id.txt_contact);
        Drawable drawable = getResources().getDrawable(R.drawable.tel_tri_2);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        headTitleView.setCompoundDrawables(null, null, drawable, null);
        headTitleView.setClickable(true);
        headTitleView.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                if (NullUtils.isEmpty(rootCompanys) || rootCompanys.size() < 1) {
                    return;
                }
                int checkedItem = 0;
                List<String> list = new ArrayList<String>();
                for (UserUserContact contact : rootCompanys) {
                    if (contact.getId().equals(companyID)) {
                        checkedItem = rootCompanys.indexOf(contact);
                    }
                    list.add(contact.getName());
                }
                new AlertDialog.Builder(getActivity()).setSingleChoiceItems(list.toArray(new String[] {}),
                    checkedItem,
                    new DialogInterface.OnClickListener() {
                        
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            UserUserContact contact = rootCompanys.get(arg1);
                            headTitleView.setText(contact.getName());
                            companyID = contact.getId();
                            editText.setText("");
                            parentIds.clear();
                            findData(null, companyID, companyID);
                            head_btn_back.setVisibility(View.GONE);
                            arg0.dismiss();
                        }
                    }).show();
            }
        });
        rootCompanys = contactUserService.searchNewGroup(null, "0", null);
        if (NullUtils.isNotEmpty(rootCompanys)) {
            headTitleView.setText(rootCompanys.get(0).getName());
            companyID = rootCompanys.get(0).getId();
        }
        companyID="0";
        editText = (EditText)view.findViewById(R.id.search_txt);
        checkBox = (CheckBox)view.findViewById(R.id.search_cb);
        groupListView = (ListView)view.findViewById(R.id.contact_group_list_item);
        head_btn_back = (ImageView)view.findViewById(R.id.head_btn_back);
        smsAdpter = new ContactAdpter(this.getActivity(), datas);
        context = this.getActivity();
        parentIds.clear();
        findData(null, companyID, companyID);
        groupListView.setOnScrollListener(this);
        
        groupListView.setAdapter(smsAdpter);
        groupListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
                final UserUserContact userContact = (UserUserContact)smsAdpter.getItem(arg2);
                if (Contact.CONTACT_TYPE_LOCAL.equals(userContact.getType())) {
                    createDialogContact(userContact);
                } else if (Contact.CONTACT_TYPE_ONLINE.equals(userContact.getType())) {
                    // 点击的是集团数据
                    createDialogContact(userContact);
                } else if (Contact.CONTACT_TYPE_GROUP.equals(userContact.getType())) {
                    // 点击分组
                    return true;
                }
                return true;
            }
            
            private void createDialogContact(final UserUserContact userContact) {
                Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("操作选择");
                builder.setItems(new String[] {"查看联系人", "编辑联系人"}, new DialogInterface.OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        
                        if (arg1 == 0) {
                            Intent intent = new Intent(getActivity(), LocalContactAddActivity.class);
                            intent.putExtra("phone", userContact.getPhone());
                            intent.putExtra("pagetype", 1);// 1是查看
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(getActivity(), LocalContactAddActivity.class);
                            intent.putExtra("phone", userContact.getPhone());
                            intent.putExtra("pagetype", 2);// 2是编辑
                            startActivity(intent);
                        }
                    }
                });
                builder.create();
                builder.show();
            }
            
        });
        
        groupListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserUserContact userContact = (UserUserContact)smsAdpter.getItem(position);
                if (Contact.CONTACT_TYPE_LOCAL.equals(userContact.getType())) {
                    String phone = userContact.getPhone();
                    // 点击的是本地通讯录
                    Intent mainIntent = new Intent(context, LocalContactAddActivity.class);
                    mainIntent.putExtra("phone", phone);
                    // 详情界面
                    mainIntent.putExtra("pagetype", 1);
                    startActivity(mainIntent);
                    
                } else if (Contact.CONTACT_TYPE_ONLINE.equals(userContact.getType())) {
                    // 点击的是集团数据
                    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                    Fragment fragment = null;
                    Bundle bundle = new Bundle();
                    fragment = new OnlineContactDetailFragment();
                    bundle.putString("userId", userContact.getId());
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < parentIds.size(); i++) {
                        if (i != 0) {
                            sb.append(",");
                        }
                        sb.append(parentIds.get(i));
                    }
                    
                    bundle.putString("parentIds", sb.toString());
                    if (fragment != null) {
                        fragment.setArguments(bundle);
                        transaction.replace(R.id.container, fragment);
                        transaction.addToBackStack(null);
                        transaction.commitAllowingStateLoss();
                    }
                } else if (Contact.CONTACT_TYPE_GROUP.equals(userContact.getType())) {
                    // 点击分组
                    head_btn_back.setVisibility(View.VISIBLE);
                    findData(null, userContact.getId(), "user");
          

                    
                }
                
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void afterTextChanged(Editable arg0) {
                String content = arg0.toString();
                if (NullUtils.isEmpty(content)) {
                    if (!parentIds.isEmpty()) {
                        parentIds.pop();
                        if (!parentIds.isEmpty()) {
                            String id = parentIds.pop();
                            findData(null, id, "user");
                            return;
                        }
                    }
                    findData(null, companyID, "user");
                } else {
                    head_btn_back.setVisibility(View.VISIBLE);
                    findData(arg0.toString(), null, "user");
                }
                
            }
            
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }
            
            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
                
            }
            
        });
        //
        checkBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(CompoundButton button, boolean isChecked) {
            }
            
        });
        head_btn_back.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View ediview) {
                if (NullUtils.isNotEmpty(editText.getText().toString())) {
                    editText.setText("");
                    return;
                }
                
                if (parentIds.isEmpty()) {
                    head_btn_back.setVisibility(View.GONE);
                    return;
                }
                parentIds.pop();
                if (parentIds.isEmpty()) {
                    head_btn_back.setVisibility(View.GONE);
                    return;
                }
                String value = parentIds.pop();
                if (parentIds.isEmpty()) {
                    head_btn_back.setVisibility(View.GONE);
                }
                if (value.contains("select")) {
                    findData(value.substring(6), null, "user");
                } else {
                    findData(null, value, "user");
                }
            }
        });
//        if(!sharedPreferences.contains("onLineUpdateTime")) {
//        	Toast.makeText(context, "请先进行单位通讯录同步!", Toast.LENGTH_LONG).show();
//        }
        return view;
    }
    
    private void findData(String... params) {
        String value = "";
        if (!parentIds.isEmpty()) {
            value = parentIds.lastElement();
        }
        
        if (params != null && NullUtils.isNotEmpty(params[0])) {
            if (value.contains("select") && !parentIds.isEmpty()) {
                parentIds.pop();
            }
            parentIds.add("select" + params[0]);
        } else {
            parentIds.add(params[1]);
        }
        if (parentIds.size()==1) {
            head_btn_back.setVisibility(View.GONE);
        }else{
            head_btn_back.setVisibility(View.VISIBLE);
        }
        
        new BaseTask<String, String, List<UserUserContact>>(getActivity()) {
            
            @Override
            protected void onSuccess(List<UserUserContact> result) {
                smsAdpter.removeAll();
                smsAdpter.notifyDataSetChanged();
                smsAdpter.addCollection(result);
                smsAdpter.notifyDataSetChanged();
            }
            
            @Override
            protected List<UserUserContact> doInBack(String... params)
                throws Exception {
                List<UserUserContact> list = new ArrayList<UserUserContact>();
                
                if (params != null && params.length == 3) {
                    list.addAll(contactUserService.searchContactUser(params[0], params[1], companyID));
                }
                if (NullUtils.isEmpty(params[0]) || checkBox.isChecked() && NullUtils.isNotEmpty(params[0])) {
                	try{
                		list.addAll(contactUserService.searchNewGroup(params[0], params[1], companyID));
                	}catch(Exception e) {
                		e.printStackTrace();
                	}
                    
                }
                return list;
            }
        }.execute(params);
    }
    
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.visibleItemCount = visibleItemCount;
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
    }
    
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {/*
                                                                          * int itemsLastIndex = smsAdpter.getCount() -
                                                                          * 1; // 数据集最后一项的索引 int lastIndex =
                                                                          * itemsLastIndex + 1; // 加上底部的loadMoreView项 if
                                                                          * (scrollState ==
                                                                          * OnScrollListener.SCROLL_STATE_IDLE &&
                                                                          * visibleLastIndex == lastIndex) {
                                                                          * progressView.setVisibility(View.VISIBLE);
                                                                          * new Handler().postDelayed(new Runnable() {
                                                                          * 
                                                                          * @Override public void run() { loadMore(); }
                                                                          * 
                                                                          * }, 2000); }
                                                                          */
    }
    
    private void loadMore() {
        if (!isGroup) {
            smsAdpter.removeAll();
            List<UserUserContact> list =
                contactUserService.searchContactUser(null, Contact.CONTACT_TYPE_ONLINE, companyID);
            smsAdpter.addCollection(list);
            
            smsAdpter.notifyDataSetChanged(); // 数据集变化后,通知adapter
            groupListView.setSelection(visibleLastIndex - visibleItemCount + 1); // 设置选中项
            progressView.setVisibility(View.GONE);
        }
        
    }
    
    @Override
    public void onResume() {
        
        if (flag) {
            smsAdpter.removeAll();
            smsAdpter.notifyDataSetChanged();
            List<UserUserContact> list = contactUserService.searchNewGroup(null, clickId, companyID);
            list.addAll(contactUserService.searchContactUser(null, clickId, companyID));
            smsAdpter.addCollection(list);
            smsAdpter.notifyDataSetChanged();
            flag = false;
        }
        super.onResume();
    }
    
}
